//
//  LHDateSelectViewController.swift
//  TJJPT
//
//  Created by FENGYL on 2017/7/17.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

import UIKit
import SVProgressHUD

class LHDateSelectViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource {
    
    @IBOutlet weak var todayButton: UIButton!
    @IBOutlet weak var yesterdayButton: UIButton!
    @IBOutlet weak var customButton: UIButton!
    @IBOutlet weak var searchButton: UIButton!
    
    @IBOutlet weak var timeView: UIView!
    @IBOutlet weak var timeViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var startTimeLabel: UILabel!
    @IBOutlet weak var endTimeLabel: UILabel!
    
    @IBOutlet weak var startTimeDateButton: UIButton!
    @IBOutlet weak var startTimeTimeButton: UIButton!
    @IBOutlet weak var endTimeDateButton: UIButton!
    @IBOutlet weak var endTimeTimeButton: UIButton!
    
    
    var blackBackgroudView:UIView?
    var datePicker:UIDatePicker?
    var timePickerView:UIPickerView?
    
    let startTimeDateTag = 20001
    let startTimeTimeTag = 20002
    let endTimeDateTag = 20003
    let endTimeTimeTag = 20004
    
    var selectTime = "00:00:00"
    

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setUpView(){
        
        // MARK: 标题
        self.title = NSLocalizedString(LOCALIZABLE_STRING_LOCATION_HISTORY, comment: "")
        
        // MARK: 隐藏时间
        timeView.isHidden = true
        timeViewHeight.constant = 0
        
        // MARK: 顶上三个按钮文字
        todayButton.setTitle(NSLocalizedString(LOCALIZABLE_STRING_TODAY, comment: ""), for: .normal)
        yesterdayButton.setTitle(NSLocalizedString(LOCALIZABLE_STRING_YESTERDAY, comment: ""), for: .normal)
        customButton.setTitle(NSLocalizedString(LOCALIZABLE_STRING_CUSTOM, comment: ""), for: .normal)
        
        // MARK: 搜索按钮
        searchButton.setTitle(NSLocalizedString(LOCALIZABLE_STRING_SEARCH, comment: ""), for: .normal)
        
        // MARK: 开始结束时间label
        startTimeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_START_TIME, comment: "")
        endTimeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_END_TIME, comment: "")
        
        
        setTodayDate()
        
        print(startTimeDateButton.titleLabel?.text ?? "")
        
    }

    // MARK: - 今天
    @IBAction func touchTodayButton(_ sender: Any) {
        
        todayButton.isSelected = true
        yesterdayButton.isSelected = false
        customButton.isSelected = false
        
        timeView.isHidden = true
        timeViewHeight.constant = 0
        
        setTodayDate()
        
        
    }
    
    
    // MARK: - 昨天
    @IBAction func touchYesterdayButton(_ sender: Any) {
        
        todayButton.isSelected = false
        yesterdayButton.isSelected = true
        customButton.isSelected = false
        
        timeView.isHidden = true
        timeViewHeight.constant = 0
        
        setYesterdayDate()
    }
    
    // MARK: - 自定义
    @IBAction func touchCustomButton(_ sender: Any) {
        
        todayButton.isSelected = false
        yesterdayButton.isSelected = false
        customButton.isSelected = true
        
        timeView.isHidden = false
        timeViewHeight.constant = 150
        
        setTodayDate()
        
    }
    
    // MARK: - 搜索按钮
    @IBAction func touchSearchButton(_ sender: Any) {
        

        
        
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER + " " + STATIC_VALUE_TIME_FORMATTER
        
        let startDateString = (startTimeDateButton.titleLabel?.text)! + " " + (startTimeTimeButton.titleLabel?.text)!
        let endDateString = (endTimeDateButton.titleLabel?.text)! + " " + (endTimeTimeButton.titleLabel?.text)!
        
        let startDate = dateFormatter.date(from: startDateString)
        let endDate = dateFormatter.date(from: endDateString)
        
        let startNumber = NSNumber.init(value: (startDate?.timeIntervalSince1970)!)
        let endNumber = NSNumber.init(value: (endDate?.timeIntervalSince1970)!)
        
        
        
        
        SVProgressHUD.show()
        
        NetworkCommand.getHistoryTrackPoiDataByTime(startTime: startNumber, endTime: endNumber, serialNumber: nil, id: nil, clientType: nil, tokenPass: nil, success: { (response) in
            
            if ((response as? NSArray) != nil) {
                
                let array:NSArray = response as! NSArray
                
                if array.count > 0 {
                    
                    SVProgressHUD.dismiss()
                    
                    let alertController = UIAlertController.init(title: NSLocalizedString(LOCALIZABLE_STRING_HAVE_LOCATION_HISTORY, comment: ""), message: nil, preferredStyle: .alert)
                    
                    
                    let cancelAction = UIAlertAction.init(title: NSLocalizedString(LOCALIZABLE_STRING_CANCEL, comment: ""), style: .cancel, handler: nil)
                    
                    let playAction = UIAlertAction.init(title: NSLocalizedString(LOCALIZABLE_STRING_PLAY, comment: ""), style: .destructive, handler: { (UIAlertAction) in
                        
                        let storyboard = UIStoryboard.init(name: "LocationHistory", bundle: Bundle.main)
                        
                        let playController:LHPlayViewController = storyboard.instantiateViewController(withIdentifier: "LHPlayViewController") as! LHPlayViewController
                        
                        playController.dataArray = array
                        
                        self.show(playController, sender: nil)
                        
                    })
                    
                    alertController.addAction(cancelAction)
                    alertController.addAction(playAction)
                    
                    self.present(alertController, animated: true, completion: nil)
                    
                    return
                    
                }
                
            }
            
            SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_FAILURE, comment: ""))
            
            SVProgressHUD.dismiss(withDelay: 1)
            
            
        }) { (Error) in
            
            SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_FAILURE, comment: ""))

            SVProgressHUD.dismiss(withDelay: 1)
            
        }
        
        
    }

    // MARK: - 设置今天时间
    func setTodayDate() {
        
        let date = Date.init()
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER
        
        let dateString = dateFormatter.string(from: date)
        
        
        
        startTimeDateButton.setTitle(dateString, for: .normal)
        
        endTimeDateButton.setTitle(dateString, for: .normal)
        
        startTimeTimeButton.setTitle("00:00:00", for: .normal)
        
        endTimeTimeButton.setTitle("23:59:59", for: .normal)
        
        
        
        
        print(startTimeDateButton.titleLabel?.text ?? "")
        print(startTimeTimeButton.titleLabel?.text ?? "")
        print(endTimeDateButton.titleLabel?.text ?? "")
        print(endTimeTimeButton.titleLabel?.text ?? "")
        
        
    }
    
    func setYesterdayDate() {
        
        let date = Date.init(timeIntervalSinceNow: -(24 * 60 * 60))
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER
        
        let dateString = dateFormatter.string(from: date)
        
        
        
        startTimeDateButton.setTitle(dateString, for: .normal)
        
        endTimeDateButton.setTitle(dateString, for: .normal)
        
        startTimeTimeButton.setTitle("00:00:00", for: .normal)
        
        endTimeTimeButton.setTitle("23:59:59", for: .normal)
        
        
        
        
        print(startTimeDateButton.titleLabel?.text ?? "")
        print(startTimeTimeButton.titleLabel?.text ?? "")
        print(endTimeDateButton.titleLabel?.text ?? "")
        print(endTimeTimeButton.titleLabel?.text ?? "")
        
    }
    
    // MARK: - 开始日期
    @IBAction func touchStartTimeDateButton(_ sender: Any) {
        
        datePicker = UIDatePicker.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200, width: STATIC_VALUE_SCREEN_WIDTH, height: 200))
        
        datePicker?.tag = startTimeDateTag
        
        datePicker?.backgroundColor = UIColor.white
        
        datePicker?.datePickerMode = .date
        
        
        
        let toolBar = UIToolbar.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200 - 30, width: STATIC_VALUE_SCREEN_WIDTH, height: 30))
        
        toolBar.barStyle = .default
        
        let fixedBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        
        let confirmBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CONFIRM, comment: ""), style: .done, target: self, action: #selector(datePickFinish))
        
        let cancelBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CANCEL, comment: ""), style: .done, target: self, action: #selector(datePickCancel))
        
        toolBar.setItems([fixedBarButtonItem,cancelBarButtonItem,confirmBarButtonItem], animated: true)
        
        
        
        
        let window = UIApplication.shared.keyWindow
        
        blackBackgroudView = UIView.init(frame: (window?.bounds)!)
        
        blackBackgroudView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        
        blackBackgroudView?.addSubview(datePicker!)
        
        blackBackgroudView?.addSubview(toolBar)
        
        window?.addSubview(blackBackgroudView!)
        
        
        
        
        
    }
    
    // MARK: - 开始时间
    @IBAction func touchStartTImeTimeButton(_ sender: Any) {
        
        
        selectTime = (startTimeTimeButton.titleLabel?.text)!
        
        
        
        timePickerView = UIPickerView.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200, width: STATIC_VALUE_SCREEN_WIDTH, height: 220))
        
        timePickerView?.tag = startTimeTimeTag
        
        timePickerView?.backgroundColor = UIColor.white
        
        timePickerView?.delegate = self
        
        timePickerView?.dataSource = self
        
        timePickerView?.tag = startTimeTimeTag
        
        
        
        let toolBar = UIToolbar.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200 - 30, width: STATIC_VALUE_SCREEN_WIDTH, height: 30))
        
        toolBar.barStyle = .default
        
        let fixedBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        
        let confirmBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CONFIRM, comment: ""), style: .done, target: self, action: #selector(datePickFinish))
        
        let cancelBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CANCEL, comment: ""), style: .done, target: self, action: #selector(datePickCancel))
        
        toolBar.setItems([fixedBarButtonItem,cancelBarButtonItem,confirmBarButtonItem], animated: true)
        
        
        
        
        let window = UIApplication.shared.keyWindow
        
        blackBackgroudView = UIView.init(frame: (window?.bounds)!)
        
        blackBackgroudView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        
        blackBackgroudView?.addSubview(timePickerView!)
        
        blackBackgroudView?.addSubview(toolBar)
        
        window?.addSubview(blackBackgroudView!)
        
    }
    
    
    // MARK: - 结束日期
    @IBAction func touchEndTimeDateButton(_ sender: Any) {
        
        datePicker = UIDatePicker.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200, width: STATIC_VALUE_SCREEN_WIDTH, height: 200))
        
        datePicker?.tag = endTimeDateTag
        
        datePicker?.backgroundColor = UIColor.white
        
        datePicker?.datePickerMode = .date
        
        
        
        let toolBar = UIToolbar.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200 - 30, width: STATIC_VALUE_SCREEN_WIDTH, height: 30))
        
        toolBar.barStyle = .default
        
        let fixedBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        
        let confirmBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CONFIRM, comment: ""), style: .done, target: self, action: #selector(datePickFinish))
        
        let cancelBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CANCEL, comment: ""), style: .done, target: self, action: #selector(datePickCancel))
        
        toolBar.setItems([fixedBarButtonItem,cancelBarButtonItem,confirmBarButtonItem], animated: true)
        
        
        
        
        let window = UIApplication.shared.keyWindow
        
        blackBackgroudView = UIView.init(frame: (window?.bounds)!)
        
        blackBackgroudView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        
        blackBackgroudView?.addSubview(datePicker!)
        
        blackBackgroudView?.addSubview(toolBar)
        
        window?.addSubview(blackBackgroudView!)
        
    }
    
    
    // MARK: - 结束时间
    @IBAction func touchEndTimeTimeButton(_ sender: Any) {
        
        
        selectTime = (endTimeTimeButton.titleLabel?.text)!
        
        
        
        timePickerView = UIPickerView.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200, width: STATIC_VALUE_SCREEN_WIDTH, height: 220))
        
        timePickerView?.tag = startTimeTimeTag
        
        timePickerView?.backgroundColor = UIColor.white
        
        timePickerView?.delegate = self
        
        timePickerView?.dataSource = self
        
        timePickerView?.tag = endTimeTimeTag
        
        
        
        let toolBar = UIToolbar.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200 - 30, width: STATIC_VALUE_SCREEN_WIDTH, height: 30))
        
        toolBar.barStyle = .default
        
        let fixedBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        
        let confirmBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CONFIRM, comment: ""), style: .done, target: self, action: #selector(datePickFinish))
        
        let cancelBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CANCEL, comment: ""), style: .done, target: self, action: #selector(datePickCancel))
        
        toolBar.setItems([fixedBarButtonItem,cancelBarButtonItem,confirmBarButtonItem], animated: true)
        
        
        
        
        let window = UIApplication.shared.keyWindow
        
        blackBackgroudView = UIView.init(frame: (window?.bounds)!)
        
        blackBackgroudView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        
        blackBackgroudView?.addSubview(timePickerView!)
        
        blackBackgroudView?.addSubview(toolBar)
        
        window?.addSubview(blackBackgroudView!)
        
    }
    
    // MARK: - pickerView delegate,datasource
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        
        return 3
        
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        
        if component == 0 {
            
            return 24
            
        }else if component == 1 {
            
            return 60
            
        }else if component == 2 {
            
            return 60
            
        }
        
        return 0
        
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        return String.init(format: "%02d", row)
        
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        
        if component == 0 {
            
            let startIndex = selectTime.startIndex
            
            let endIndex = selectTime.index(startIndex, offsetBy: 2)
            
            let range = Range<String.Index>.init(uncheckedBounds: (lower: startIndex, upper: endIndex))
            
            let string = String.init(format: "%02d", row)
            
            selectTime = selectTime.replacingCharacters(in: range, with: string)
            
        }else if component == 1 {
            
            let startIndex = selectTime.index(selectTime.startIndex, offsetBy: 3)
            
            let endIndex = selectTime.index(selectTime.startIndex, offsetBy: 5)
            
            let range = Range<String.Index>.init(uncheckedBounds: (lower: startIndex, upper: endIndex))
            
            let string = String.init(format: "%02d", row)
            
            selectTime = selectTime.replacingCharacters(in: range, with: string)
            
        }else if component == 2 {
            
            let startIndex = selectTime.index(selectTime.startIndex, offsetBy: 6)
            
            let endIndex = selectTime.endIndex
            
            let range = Range<String.Index>.init(uncheckedBounds: (lower: startIndex, upper: endIndex))
            
            let string = String.init(format: "%02d", row)
            
            selectTime = selectTime.replacingCharacters(in: range, with: string)
            
        }
        
    }
    
    // MARK: - datePickerCancel
    func datePickCancel() {
        
        blackBackgroudView?.removeFromSuperview()
        
    }
    
    // MARK: - datePicker回调
    func datePickFinish() {
        
        let date = datePicker?.date
        
        if datePicker?.tag == startTimeDateTag {
            
            let dateFormatter = DateFormatter.init()
            dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER
            let dateString = dateFormatter.string(from: date!)
            
            startTimeDateButton.setTitle(dateString, for: .normal)
            
            
        }else if datePicker?.tag == endTimeDateTag {
            
            let dateFormatter = DateFormatter.init()
            dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER
            let dateString = dateFormatter.string(from: date!)
            
            endTimeDateButton.setTitle(dateString, for: .normal)
            
        }
        
        if timePickerView?.tag == startTimeTimeTag {
            
            startTimeTimeButton.setTitle(selectTime, for: .normal)
            
        }else if timePickerView?.tag == endTimeTimeTag {
            
            endTimeTimeButton.setTitle(selectTime, for: .normal)
            
        }
        
        blackBackgroudView?.removeFromSuperview()
        
        
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
